package com.cheyunkeji.er.view.evaluate;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;

/**
 * Created by zhy on 15/5/14.
 */
public class ColourImageBaseLayerView extends ImageView {

    private static final String TAG = ColourImageBaseLayerView.class.getSimpleName();

    private float width;
    private float height;
    private Bitmap[] mDrawables;



    public ColourImageBaseLayerView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }


    public void setBitmaps(Bitmap[] bitmap) {
        this.mDrawables = bitmap;
        invalidate();
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mDrawables != null && mDrawables.length > 0) {
            for (int i = 0; i < mDrawables.length; i++) {
                RectF rectF = new RectF(0, 0, getWidth(), getHeight());
                canvas.drawBitmap(mDrawables[i], null, rectF, null);
            }

            width = getWidth() * 1.0f / mDrawables[0].getWidth();
            height = getHeight() * 1.0f / mDrawables[0].getHeight();
        }

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        final float x = event.getX();
        final float y = event.getY();
        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            int index = findDrawable(x / width, y / height) ;
            if(0 != index)
            listener.onAreaTouched(index);

        }
        return super.onTouchEvent(event);
    }

    /**
     * 获取触摸点所在的图层的下标
     * @param x
     * @param y
     * @return
     */
    private int findDrawable(float x, float y) {

        Bitmap bitmap = null;

//        最底部的为汽车框架轮廓图，所以从第二张开始遍历，而不是从下标为0开始
        for (int i = 1; i < mDrawables.length; i++) {
            bitmap = mDrawables[i];
            try {
                int pixel = bitmap.getPixel((int) x, (int) y);
                if (pixel == Color.TRANSPARENT) {
                    continue;
                }
            } catch (Exception e) {
                continue;
            }
            return i;
        }
        return 0 ;  //当触摸点不在26个图层所在的有效区域时，返回标志位0

    }


    private OnColorAreaTouchedListener listener ;

    public void setListener(OnColorAreaTouchedListener listener) {
        this.listener = listener;
    }

    /**
     * 色块区域触摸监听回调
     */
    public interface OnColorAreaTouchedListener{

        void onAreaTouched(int areaIndex);
    }

}
